package com.icinfo.cloud.provider.handler;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.Md5Util;
import com.icinfo.cloud.provider.logs.model.AppAuthorizationBusiRequestLog;
import com.icinfo.cloud.provider.logs.service.IAppAuthorizationBusiRequestLogService;
import com.icinfo.cloud.provider.punish.service.IConfigAppAuthorizationRecordService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * 描述：app接入授权处理
 *
 * @Author zhengqiang
 * @Date 2022/8/16 17:49
 **/
@Component
@Aspect
@Slf4j
public class AppAuthorizationHandler {

    @Resource
    private IConfigAppAuthorizationRecordService configAppAuthorizationRecordService;
    @Resource
    private IAppAuthorizationBusiRequestLogService appAuthorizationBusiRequestLogService;

    @Pointcut("execution(* com.icinfo.cloud.provider.punish.controller.SimpleCaseApiController.saveSimpleCaseTemporary(..))"+
            "|| execution(* com.icinfo.cloud.provider.peripheralinterface.zszf.controller.HandLawInterfaceController.*(..))" )
    public void controllerPointcut(){}

    @Before("controllerPointcut()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        log.info("Before：url={}",request.getRequestURL());
        //获取appId,请求时间戳和安全码
        String appId = "";
        String requestTime = "";
        String security = "";
        String paramStr = "";
        for(Object temp : joinPoint.getArgs()){
            if (!ObjectUtils.isEmpty(temp)) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(temp);
                paramStr = jsonObject.toJSONString();
                log.info("param= {} ", jsonObject);
                appId = jsonObject.getString("caseSourceAppId");
                requestTime = jsonObject.getString("requestTime");
                security = jsonObject.getString("security");
            }
        }

        //保存请求日志
        AppAuthorizationBusiRequestLog requestLog = new AppAuthorizationBusiRequestLog();
        if (ObjectUtil.isNotEmpty(request.getRequestURL())) {
            requestLog.setRequestUrl(request.getRequestURL().toString());
        }
        requestLog.setAppId(appId);
        requestLog.setRequestContent(paramStr);
        appAuthorizationBusiRequestLogService.saveAppAuthorizationBusiRequestLog(requestLog);

        if (ObjectUtils.isEmpty(appId) || ObjectUtils.isEmpty(requestTime)) {
            throw new BusinessException("应用id及请求时间戳不能为空");
        }

        //查询应授权记录
        String appKey = configAppAuthorizationRecordService.getAppKeyByAppId(appId);
        if (ObjectUtils.isEmpty(appKey)) {
            throw new BusinessException("应用未授权-appId:" + appId);
        }

        //验证安全码是否正确
        //加密方法MD5(appId + appKey + requestTime)
        String localSecurity = "";
        try {
            localSecurity = Md5Util.md5(appId + appKey + requestTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!localSecurity.equals(security)) {
            throw new BusinessException("应用安全码有误");
        }

    }

    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        System.out.println("------------------"+System.currentTimeMillis());
        System.out.println(Md5Util.md5("TASKCENTER_HANDLAW" + "a6f9b2164d8e9e350aadae61785b3de7" + "1681982303286"));
    }

}
